package com.pvdnc.encrypt;

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Objects;

public class RSAKey {

    private static KeyPairGenerator getGenerator(int keySize){
        try {
            KeyPairGenerator generator= KeyPairGenerator.getInstance(RSA.RSA_ALGORITHM);
            generator.initialize(keySize);
            return generator;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] keyToData(Key key){
        return key.getEncoded();
    }

    public static RSAPublicKey getPublicKey(byte[] keyData) {
        try {
            KeyFactory factory = KeyFactory.getInstance(RSA.RSA_ALGORITHM);
            KeySpec keySpec = new X509EncodedKeySpec(keyData);
            return (RSAPublicKey) factory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static RSAPrivateKey getPrivateKey(byte[] keyData){
        try {
            KeyFactory factory = KeyFactory.getInstance(RSA.RSA_ALGORITHM);
            KeySpec keySpec = new PKCS8EncodedKeySpec(keyData);
            return (RSAPrivateKey) factory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
            return null;
        }

    }

    public RSAPublicKey getPublicKey() {
        return getPublicKey(mPublicKey);
    }

    public RSAPrivateKey getPrivateKey() {
        return getPrivateKey(mPrivateKey);
    }

    public byte[] mPublicKey;

    public byte[] mPrivateKey;

    public RSAKey(int keySize){
        KeyPairGenerator generator=getGenerator(keySize);
        Objects.requireNonNull(generator);
        KeyPair keyPair= generator.generateKeyPair();
        mPublicKey = keyToData(keyPair.getPublic());
        mPrivateKey=keyToData(keyPair.getPrivate());
    }

    public RSAKey(){
        this(2048);
    }
}
